// m

// 给你单链表的头指针head和两个整数left和right，其中left <= right，请你反转从位置left到right的链表节点，返回反转后的链表

const { ListNode, LinkedList } = require('../../1. 链表基础/1. 建立线性链表')

function reverseBetween(head, left, right) {
    const dummyNode = new ListNode(-1)
    dummyNode.next = head  // 虚拟头节点

    let pre = dummyNode
    for (let i = 0; i < left - 1; i++) {
        pre = pre.next
    }
    let rightNode = pre
    for (let i = 0; i < right - left + 1; i++) {
        rightNode = rightNode.next
    }
    // 保留leftNode
    let leftNode = pre.next
    // 保留rightNode
    let curr = rightNode.next

    // 切断left到right的子链
    pre.next = null
    rightNode.next = null

    reverseList(leftNode)

    pre.next = rightNode
    leftNode.next = curr
    return dummyNode.next

}

function reverseList(head) {
    let pre = null
    let cur = head
    while (cur !== null) {
        let next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    }
    return pre
}

let head = [1, 2, 3, 4, 5], left = 2, right = 4
let node = new LinkedList(head)

console.log(reverseBetween(node.head, left, right));